package com.cyan.app.workflow.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.cyan.app.workflow.AppData;
import com.cyan.app.workflow.R;
import com.cyan.app.workflow.activity.SFC.SFCActivity;
import com.cyan.app.workflow.activity.TQM.TQMActivity;
import com.cyan.app.workflow.activity.VM.VMActivity;
import com.cyan.app.workflow.activity.WHM.WHMActivity;
import com.cyan.app.workflow.base.fragment.BaseFragment;
import com.cyan.app.workflow.bean.HomeBean;
import com.cyan.app.workflow.fragment.lunbo.BannerFragment;
import com.cyan.app.workflow.util.AppUtils;
import com.cyan.app.workflow.util.FileUtils;
import com.cyan.app.workflow.util.ModuleConstants;
import com.cyan.app.workflow.util.ModuleUtil;
import com.cyan.app.workflow.util.RuntimeContext;
import com.cyan.app.workflow.widget.NoScrollGridView;
import com.cyan.app.workflow.widget.PullToRefresh.PullToRefreshBase;
import com.cyan.app.workflow.widget.PullToRefresh.PullToRefreshDefine;
import com.cyan.app.workflow.widget.PullToRefresh.PullToRefreshExpandableListView;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by GivenTang on 2015/11/1.
 */
public class OperationFragment extends BaseFragment {
    public static final String TAG = "OperationFragment";
    public static final String MODULE_ID = "ModuleId";

    private PullToRefreshExpandableListView lv_ptrl_lot;
    private ExpandableListView lv_mListView;
    private HomeAdapter mHomeAdapter;

    private BannerFragment mBanner;
    private View mBannerLayout;
    private Handler mHomeHandler = new Handler();
    private List<HomeBean.ModuleBean> homeData = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        _RootView = inflater.inflate(R.layout.layout_operation, null);
        mBanner = new BannerFragment(getActivity(), mHomeHandler);
        return _RootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mBanner != null) {
            mBanner.pause();
            mBanner.uninitBanner();
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mBanner != null) {
            mBanner.start();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mBanner != null) {
            mBanner.pause();
        }
    }

    private void initView() {
        lv_ptrl_lot = (PullToRefreshExpandableListView) _RootView.findViewById(R.id.lv_mh_ptrl_lot);
        lv_ptrl_lot.setLastTimeSaveKey(PullToRefreshDefine.SaveKey.KEY_HOME_LOTS);
        lv_mListView = lv_ptrl_lot.getRefreshableView();
        lv_mListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
        lv_ptrl_lot.setPullToRefreshEnabled(false);
        if (mBannerLayout == null) {
            mBannerLayout = mBanner.createLunBoView(AppData.getInstance().getScreenWidth());
            mBanner.initBanner();
        }
        lv_mListView.addHeaderView(mBannerLayout);

        lv_ptrl_lot.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (lv_ptrl_lot.getRefreshType() == PullToRefreshExpandableListView.MODE_PULL_DOWN_TO_REFRESH) {
                    initData();
                }
            }
        });
        mHomeAdapter = new HomeAdapter(getActivity());
        lv_mListView.setAdapter(mHomeAdapter);
    }

    //初始化数据
    private void initData() {
        String json = null;
        try {
            if (getActivity() == null)
                return;
            json = FileUtils.getFileContent(getActivity().getAssets().open("home.json"));
            HomeBean homeBean = new Gson().fromJson(json, HomeBean.class);
            homeData.clear();
            homeData.addAll(homeBean.getData());
            mHomeAdapter.notifyDataSetChanged();
            lv_ptrl_lot.saveLastRefreshTime();
            lv_ptrl_lot.onRefreshComplete();
           /* VolleyUtil.sendStringRequestByGet(getActivity(), HttpConfig.HTTP_HOME_SERVER_URL, TAG, null, null, new CommHttpListener<Object>() {
                @Override
                public void onResponse(String result) {
                    super.onResponse(result);
                    if (result == null) {
                        return;
                    }

                    HomeBean homeBean = new Gson().fromJson(result, HomeBean.class);
                    homeData.clear();
                    homeData.addAll(homeBean.getData());
                    mHomeAdapter.notifyDataSetChanged();
                    lv_ptrl_lot.saveLastRefreshTime();
                    lv_ptrl_lot.onRefreshComplete();
                }
            });*/
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class HomeAdapter extends BaseExpandableListAdapter {
        private Context context;

        public HomeAdapter(Context context) {
            this.context = context;
        }

        @Override
        public void notifyDataSetChanged() {
            super.notifyDataSetChanged();
            for (int i = 0; i < getGroupCount(); i++) {
                lv_mListView.expandGroup(i);
            }
        }

        @Override
        public int getGroupCount() {
            return homeData != null ? homeData.size() : 0;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return 1;
        }

        @Override
        public Object getGroup(int groupPosition) {
            return groupPosition;
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(context).inflate(R.layout.home_section_item, parent, false);
            ((TextView) convertView.findViewById(R.id.section_title)).setText(homeData.get(groupPosition).getModuleName()+"");
            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(context).inflate(R.layout.home_main_lotts, null, false);
            NoScrollGridView homeLottsGridview = (NoScrollGridView) convertView.findViewById(R.id.home_lotts_gridview);
            HomeModuleAdapter homeLottsAdapter = new HomeModuleAdapter();
            homeLottsAdapter.setmData(homeData.get(groupPosition).getFuncInfo());
            homeLottsGridview.setAdapter(homeLottsAdapter);
            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }

    }

    private class HomeModuleAdapter extends BaseAdapter {

        private List<HomeBean.Module> mData = new ArrayList<>();

        public void setmData(List<HomeBean.Module> mData) {
            this.mData.clear();
            this.mData.addAll(mData);
        }

        @Override
        public int getCount() {
            return this.mData.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = View.inflate(getActivity(), R.layout.home_lott_child_item, null);
            TextView plusAwards = (TextView)convertView.findViewById(R.id.plus_awards);
            ImageView lottIcon = (ImageView) convertView.findViewById(R.id.lott_icon);
            TextView lottName = (TextView) convertView.findViewById(R.id.lott_title);
            lottName.setText(mData.get(position).getName());
            TextView describle = (TextView) convertView.findViewById(R.id.lott_describle);
            describle.setText(mData.get(position).getCode());

            int moduleID = mData.get(position).getID();
            lottIcon.setImageResource(ModuleUtil.getIconByID(moduleID));
            /*if(moduleID>2){
                plusAwards.setText("待开发");
            }
            else {*/
                plusAwards.setVisibility(View.INVISIBLE);
            //}
            convertView.setOnClickListener(mLottClickListener);
            convertView.setTag(moduleID);
            return convertView;
        }
    }

    private View.OnClickListener mLottClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           if(homeData.size()==0) return;
            //if(homeData.size()< ((Integer)view.getTag()+1)) return;
            HomeBean.ModuleBean moduleBean = homeData.get(0);
            HomeBean.Module module = moduleBean.getFuncInfo().get((Integer)view.getTag() -1);
            if(module == null) return;
            int moduleId = module.getID();
            Intent intent = new Intent();
            intent.putExtra(RuntimeContext.FROM, TAG);
            intent.putExtra(MODULE_ID, moduleId);
            switch (moduleId){
                case ModuleConstants.MODULE_ID_SFC: //工单管理
                    intent.setClass(getActivity(), SFCActivity.class);
                    break;
                case ModuleConstants.MODULE_ID_WHM: //仓库管理
                    intent.setClass(getActivity(), WHMActivity.class);
                    break;
                case ModuleConstants.MODULE_ID_TQM: //质量管理
                    intent.setClass(getActivity(), TQMActivity.class);
                    break;
                case ModuleConstants.MODULE_ID_VM: //车辆管理
                    intent.setClass(getActivity(), VMActivity.class);
                    break;
                default:
                    //intent.setClass(getActivity(), SFCActivity.class);
                    AppUtils.showTip(getActivity(), "该模块拼命开发中，敬请期待");
                    return;
            }
            getActivity().startActivity(intent);
        }
    };
}
